 //
//  PredictRequestLogic.m
//  Prophecy
//
//  Created by Topsun on 14-7-28.
//  Copyright (c) 2014年 Bloominglife. All rights reserved.
//

#import "AProjectRequestLogic.h"
#import "AProjectNetRequest.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#import <objc/runtime.h>
#import "InstanceFactory.h"
#import <AdSupport/AdSupport.h>
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "CommonParameterManager.h"

static AProjectRequestLogic * s_predictRequestLogic = nil;

@implementation AProjectRequestLogic

+ (AProjectRequestLogic*) defaultRequestLogic
{
    @synchronized( self ) {
        if( nil == s_predictRequestLogic ) {
            s_predictRequestLogic = [[AProjectRequestLogic alloc] init];
            [s_predictRequestLogic addNotificationCenter];
        }
    }
    
    return s_predictRequestLogic;
}

/**
 *  初始化网络框架
 */
+ (void) initRequestLogic
{
    // 初始化配置器
    [ServiceConfig initServicesConfig];
    
    // 添加网络请求监听
    [NWS addInterfaceLister:[AProjectRequestLogic defaultRequestLogic]];
}

#pragma mark - NetWorkServicesInterface
- (void) netWorkServices:(AFNetworkServices*) netWorkServices         // 当前处理NetRequest对象的NetWorkServices
     startSendNetRequest:(AFNetRequest*) netRequest                   // 正在出来的NetRequest对象
            ProgressStat:(XProgressStat) stat                       // 当前进度状态
            additionInfo:(NSObject*) additionInfo                   // 附加参数，不同进度状态下，参数值有所不同
{
    switch ( stat ) {
            
            // 每次请求网络数据，都需要添加appkey参数
        case eStart:
        {
            if ( [netRequest isKindOfClass:[AProjectNetRequest class]] ) {
                
                NSDictionary * commonparaDic = [[CommonParameterManager shareManager]ObtianCommonParameter];
                
                for (NSString * key in [commonparaDic allKeys]) {
                    [netRequest.parameterEntity setPostValue:commonparaDic[key] forKey:key];
                }
            }
            break;
        }
        case eRequestComplete:
            [self requestComplete:netWorkServices NetRequest:netRequest additionInfo:additionInfo];
            break;
        default:
            break;
    }
}

- (void) requestComplete:(AFNetworkServices*) netWorkServices         // 当前处理NetRequest对象的NetWorkServices
              NetRequest:(AFNetRequest*) netRequest                   // 正在出来的NetRequest对象
            additionInfo:(NSObject*) additionInfo                   // 附加参数，不同进度状态下，参数值有所不同
{

    AProjectNetRequest * predictRequest = nil;
    
    if ( [netRequest isKindOfClass:AProjectNetRequest.class] ) {
        predictRequest = (AProjectNetRequest*)netRequest;
        
        Class classObject = NSClassFromString(predictRequest.entityName);
        if ( nil == classObject ) {
            return;
        }
        
        id responDictionaryData = netRequest.netResponse.resultData;
        
        //增加判断
        if ([responDictionaryData isKindOfClass:[NSArray class]]) {
            NSArray *entity = [classObject mj_objectArrayWithKeyValuesArray:responDictionaryData];
            predictRequest.responseEntity = entity;
        }
        else if ([responDictionaryData isKindOfClass:[NSDictionary class]]) {
            id entity = [classObject mj_objectWithKeyValues:responDictionaryData];;
            predictRequest.responseEntity = entity;
        }
        else {
            predictRequest.responseEntity = nil;
        }
    }
}

/**
 @method 添加应用程序状态通知
 @param UIApplication* 应用程序代理类对象
 @result 空
 */
- (void) addNotificationCenter
{
    UIApplication * app= [UIApplication sharedApplication];
    
    // 程序失去焦点
	[[NSNotificationCenter defaultCenter ] addObserver:self
											  selector:@selector(applicationDidEnterBackground:)
												  name:UIApplicationDidEnterBackgroundNotification
												object:app];
}

/**
 @method 移除应用程序状态通知
 @param UIApplication* 应用程序代理类对象
 @result 空
 */
- (void) removeNotificationCenter
{
    UIApplication * app= [UIApplication sharedApplication];
    
    // 程序失去焦点
	[[NSNotificationCenter defaultCenter ] removeObserver:self
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:app];
}

/**
 @method 程序进入到后台
 @param UIApplication* 应用程序代理类对象
 @result 空
 */
- (void)applicationDidEnterBackground:(UIApplication *)application
{
//    ArchiverCacheDB *db = (ArchiverCacheDB*)[InstanceFactory getCacheDBInterface];
//    [db serialize];
}

- (NSString*) signature:(NSDictionary*) posttable
{
    NSString * signature = nil;
    
    NSString * string = kServeroauth;
    NSArray * ascendingKey = [self sortArrayDesc:[posttable allKeys]];
    
    @autoreleasepool
    {
        for ( NSString *key in ascendingKey )
        {
            id obj = [posttable objectForKey:key];
            
            NSString * ress = [[obj description]stringByReplacingOccurrencesOfString:@" " withString:@""];//去掉所有空格
            NSString * res = [ress stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];//去掉两端换行符
            
            if ( [key isEqualToString:@"sign"] || [key isEqualToString:@"image"] || [key isEqualToString:@"audio"] || res.length == 0 ) {
                continue;
            }
            string = [NSString stringWithFormat:@"%@%@%@", string, key, res];
        }
        
        string = [NSString stringWithFormat:@"%@%@", string, @"123"];
        
        signature = [[NSString alloc] initWithFormat:@"%@", [self MD5EncodedString:string]];
    }
    
    return signature;
}


/**
 @method 数组升序排序
 @param array 排序的数组
 */
-(NSArray *)sortArrayDesc:(NSArray *)array{
    NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2){
        return [obj1 compare:obj2];
    }];
    return sortedArray;
}

/**
 @method MD5加密
 @param content 加密的字符串
 @result 返回加密字符串
 */
- (NSString *)MD5EncodedString:(NSString *)content{
    const char *str = [content UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    return filename;
}


@end
